<!--
 * @Author: tenet 18742176629@163.com
 * @Date: 2024/6/25 下午4:52
 * @LastEditors: tenet 18742176629@163.com
 * @LastEditTime: 2024/6/25 下午4:52
 * @FilePath: G:/block-watch-sys/src/views/assetManagement\index.vue
 * @Description: 收款地址
-->
<template>
  <!-- 查询 -->
  <div class="queryBar">
    <query-bar :title="$t('title.ReceivingAddress')">
      <!--    查询按钮-->
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-row :gutter="20" style="width: 100%;">
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item :label="$t('table.ChainName')" style="width: 100%;">
              <el-input v-model.trim="queryParams.chainName" :placeholder="$t('global.PleaseInput') + $t('table.ChainName')" clearable @input="inp1" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item :label="$t('table.CollectAddress')" style="width: 100%;">
              <el-input v-model.trim="queryParams.collectAddress" :placeholder="$t('global.PleaseInput') + $t('table.CollectAddress')"
                        clearable />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item class="btns" style="width: 100%;">
              <el-button type="primary" :icon="Search"  @click="onSubmit(queryParams.chainName, queryParams.collectAddress)"> {{ $t('button.Search') }}</el-button>
              <el-button type="default" :icon="Refresh"  plain @click="onReset">{{ $t('button.Reset') }}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </query-bar>
    <div class="query_btns">
      <el-row :gutter="8">
        <el-col :span="1.5">
          <el-button type="primary" plain :icon="Plus" @click="handleAdd">{{$t('button.Add') }}</el-button>
          <el-button type="primary" plain @click="openChangeCertificateDialog">
            {{ $t('message.ChangeCertificate') }}
          </el-button>
        </el-col>
      </el-row>
    </div>
  </div>

  <el-table :data="tableData" stripe border style="width: 100%; " size="large" v-loading="loading" max-height="600px">
    <el-table-column prop="chainName" :label="$t('table.ChainName')" width="180" align="center" />
    <el-table-column prop="feeAddress" :label="$t('table.FeeAddress')" width="auto" align="center" />
    <el-table-column prop="collectAddress" :label="$t('table.CollectAddress')" width="auto" align="center" />
    <el-table-column fixed="right" :label="$t('global.Operation')" width="150" align="center">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="handleEdit(scope)" >{{ $t('global.Update') }}</el-button>
        <el-button link type="primary" size="small" @click="updateFeeAddress(scope.row)" >{{ $t('table.updateFeeAddress') }}</el-button>
        <el-button link type="danger" size="small" @click="handleDelete(scope)" >{{ $t('global.Delete') }}</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="page">
    <el-pagination v-model:current-page="pageIndex" :page-size="pageSize" layout="total, prev, pager, next"
                   :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>

  <!--  新增资产 dialog -->
  <el-dialog v-model="addDialog" :title="$t('assetManagement.AddAsset')" width="500" center @close="resetForm">
    <el-form :model="form" :rules="rules" ref="ruleRef" label-width="auto" style="max-width: 600px">
      <el-form-item prop="chainId" :label="$t('table.ChainName')">
        <el-select v-model.trim="form.mainCoinType" :loading="loading" :placeholder="$t('assetManagement.SelectChainName')">
          <el-option v-for="(item, index) in chainList" :key="index" :label="item.chainName" :value="item.udunId" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item prop="feeAddress" :label="$t('assetManagement.FeeAddress')">
        <el-input v-model.trim="form.feeAddress" type="text" :placeholder="$t('global.PleaseInput') + $t('assetManagement.FeeAddress')" />
      </el-form-item> -->
      <el-form-item prop="collectAddress" :label="$t('assetManagement.CollectAddress')">
        <el-input v-model.trim="form.collectAddress" type="text" :placeholder="$t('global.PleaseInput') + $t('assetManagement.CollectAddress')" />
      </el-form-item>
      <el-form-item prop="code" :label="$t('global.emailCode')">
        <el-input style="width: 50%;" v-model="form.code" :placeholder="$t('global.PleaseInput') + $t('global.emailCode')"></el-input>
        <el-button style="width: 50%;" @click="getEmailCode" :disabled="isThrottled">
          <span v-show="!isThrottled">
            {{ $t('global.GetCode') }}
          </span>
          <span v-show="isThrottled">
            {{ `${remainingTime}${$t('global.reSendCode')}` }}
          </span>
        </el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCloseAdd"> {{$t('global.Cancel')}} </el-button>
        <el-button type="primary" @click="submitAdd">{{ $t('global.Submit') }}</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 更换证书 -->
  <el-dialog v-model="changeCertificateDialogVisible" :title="$t('message.ChangeCertificate')" width="500">
    <el-form>
      <el-form-item :label="$t('global.emailCode')">
        <el-input style="width: 50%;" v-model="changeForm.code" :placeholder="$t('global.PleaseInput') + $t('global.emailCode')"></el-input>
        <el-button style="width: 50%;" @click="getEmailCode" :disabled="isThrottled">
          <span v-show="!isThrottled">
            {{ $t('global.GetCode') }}
          </span>
          <span v-show="isThrottled">
            {{ `${remainingTime}${$t('global.reSendCode')}` }}
          </span>
        </el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeCertificateDialog">
          {{$t('global.Cancel')}}
        </el-button>
        <el-button type="primary" @click="submitChangeCertificate">
          {{ $t('global.Submit') }}
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!--  修改资产 dialog -->
  <el-dialog v-model="editDialog" :title="$t('assetManagement.UpdateAsset')" width="500" center @close="resetForm">
    <el-form :model="editForm" :rules="rules" ref="ruleEditRef" label-width="auto" style="max-width: 600px">
      <el-form-item :label="$t('table.ChainName')">
        <el-select v-model.trim="editForm.mainCoinType" disabled>
          <el-option v-for="(item, key) in unref(configList)" :key="key" :label="item.chainName"
                     :value="item.udunId" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item prop="feeAddress" :label="$t('assetManagement.FeeAddress')">
        <el-input v-model.trim="editForm.feeAddress" />
      </el-form-item> -->
      <el-form-item prop="collectAddress" :label="$t('assetManagement.CollectAddress')">
        <el-input v-model.trim="editForm.collectAddress" />
      </el-form-item>
      <el-form-item prop="code" :label="$t('global.emailCode')">
        <el-input style="width: 50%;" v-model="editForm.code" :placeholder="$t('global.PleaseInput') + $t('global.emailCode')"></el-input>
        <el-button style="width: 50%;" @click="getEmailCode" :disabled="isThrottled">
          <span v-show="!isThrottled">
            {{ $t('global.GetCode') }}
          </span>
          <span v-show="isThrottled">
            {{ `${remainingTime}${$t('global.reSendCode')}` }}
          </span>
        </el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCloseEdit"> {{$t('global.Cancel')}} </el-button>
        <el-button type="primary" @click="submitEdit(tag)">{{ $t('global.Submit') }}</el-button>
      </div>
    </template>
  </el-dialog>

  <!--  删除资产 dialog -->
  <el-dialog v-model="deleteDialog" :title="$t('assetManagement.DeleteAsset')" width="500" center @close="closeDeleteDialog">
    <el-form>
      <el-form-item :label="$t('global.emailCode')">
        <el-input style="width: 50%;" v-model="changeForm.code" :placeholder="$t('global.PleaseInput') + $t('global.emailCode')"></el-input>
        <el-button style="width: 50%;" @click="getEmailCode" :disabled="isThrottled">
          <span v-show="!isThrottled">
            {{ $t('global.GetCode') }}
          </span>
          <span v-show="isThrottled">
            {{ `${remainingTime}${$t('global.reSendCode')}` }}
          </span>
        </el-button>
      </el-form-item>
    </el-form>
    <template #footer #default="scope">
      <div class="dialog-footer">
        <el-button @click="closeDeleteDialog"> {{$t('global.Cancel')}} </el-button>
        <el-button type="primary" @click="submitDelete">{{ $t('global.Submit') }}</el-button>
      </div>
    </template>
  </el-dialog>



</template>

<script setup>
import { ref, onMounted, unref, reactive, watch } from 'vue'
import {Delete, Edit, Plus, Refresh, Search, Upload} from "@element-plus/icons-vue";
import {formatTimestamp} from "@/utils/timeStamp";
import queryBar from "@/components/queryBar/index.vue"
import {ElMessage, ElPagination, ElSwitch, ElTable, ElMessageBox} from "element-plus";
import {getPrivateKeyList, createPrivateKey, updatePrivateKey, getConfigList, deletePrivateKey, changePrivatePemApi, getEmailCodeApi, updateFeeAddressApi } from "@/require/api.js"
import {useI18n} from "vue-i18n";
const { t } = useI18n();
import { useUserStore } from "@/stores";

const userStore = useUserStore();

onMounted(()=>{
  getList()
  getChainList()
})

const inp1 = (v)=>{
  console.log(v)
}

const pageSize = ref(10)
const pageIndex = ref(1)
const total = ref(0)
const tableData = ref([])
const chainList = ref([])
const loading = ref(false)
const addDialog = ref(false) // 新增资产dialog
const editDialog = ref(false) // 修改资产dialog
const deleteDialog = ref(false) // 删除资产dialog
const ruleRef = ref(null)
const ruleEditRef = ref(null)
const configList = ref([])
const id = ref()
/***********************************      新增资产 start     *********************************/
// 新增资产 form
const form = reactive({
  /* chainId: '', */
  // mainCoinType: '', // udunId
  mainCoinType: undefined, // 初始化为一个空对象
  feeAddress: '',   //手续费地址
  collectAddress: '',  //归集地址
  chainName: '',
  code: '',
})

// 新增资产 dialog
async function handleAdd() {
  addDialog.value = true;
}

// 提交新增资产请求
async function submitAdd() {
    if (form.feeAddress.trim() === '' || form.collectAddress.trim() === '') {
      ElMessage.error(t('message.InputAll'))
      return
    }
    // 添加资产
    try {
      const chainData = unref(chainList.value).filter(item => item.udunId === form.mainCoinType)
      const { code, msg } = await createPrivateKey(
          {
            mainCoinType: form.mainCoinType,
            feeAddress: form.feeAddress,
            collectAddress: form.collectAddress,
            chainName: chainData[0].chainName,
            code: form.code,
          })
      // addDialog.value = false
      if (code === 200) {
        ElMessage.success(t('message.AddSuccess'))
      } else {
        ElMessage.error(msg)
      }
    } catch (e) {
      console.log(e)
    } finally {
      resetForm()
      await getList()
    }
}

/***********************************      新增资产 end     *********************************/

// 更换证书的form
const changeForm = ref({
  code: '',
});

// 控制更换证书弹出框显隐
const changeCertificateDialogVisible = ref(false);

// 打开更换证书弹出框
function openChangeCertificateDialog() {
  changeCertificateDialogVisible.value = true;
};

// 提交更换证书
function submitChangeCertificate() {
  changePrivatePem();
};

// 更换证书方法
async function changePrivatePem() {
  try {
    let res = await changePrivatePemApi();
    if (res.code === 200) {
      ElMessage.success(t('message.CertificateChangedSuccessfully'));
    } else {
      ElMessage.error(res.msg);
    }
    closeCertificateDialog();
  } catch (error) {
    console.log('changePrivatePemApi - error', error);
  }
};

// 关闭更换证书弹出框
function closeCertificateDialog() {
  changeCertificateDialogVisible.value = false;
  changeForm.value.code = '';
};

/***********************************      修改资产 start     *********************************/
// 修改表单
const editForm = reactive({
  id: '',
  mainCoinType: undefined, // 初始化为一个空对象
  // mainCoinType: '',
  feeAddress: '',   //手续费地址
  collectAddress: '',  //归集地址
  chainName: '',
  code: '',
})

// 原始值
const originalFeeAddress = ref('')
const originalCollectAddress = ref('')

// 数据删除方法
async function handleDelete(scope) {
  deleteDialog.value = true
  id.value = scope.row.id
}
// 关闭删除弹出框
function closeDeleteDialog() {
  deleteDialog.value = false;
  changeForm.value.code = '';
};

// 提交删除
async function submitDelete(){
  console.log(id.value)
  try {
    const { code, data, msg } = await deletePrivateKey( id.value, changeForm.value.code )
    if(code === 200){
      ElMessage.success(t('message.DelSuccess'))
    }else{
      ElMessage.error(msg)
    }
  }catch (e) {
    console.log(e)
  } finally {
    closeDeleteDialog();
    getList();
  }
}

// 数据更新方法
async function handleEdit({ row }) {
  editDialog.value = true
  const { data } = await getConfigList();
  configList.value = data;
  editForm.mainCoinType = row.mainCoinType;
  editForm.id = row.id
  editForm.feeAddress = row.feeAddress
  editForm.collectAddress = row.collectAddress

  // 确保originalFeeAddress, originalCollectAddress 是在editDialog打开时保存的原始值
  // 例如，在editDialog打开时保存原始值:
  originalFeeAddress.value = editForm.feeAddress;
  originalCollectAddress.value = editForm.collectAddress;
}

// 提交修改
async function submitEdit(tag) {
  // 修改资产
  try {
    const chainData = unref(configList).filter(item => item.udunId === editForm.mainCoinType)
    const { code, msg } = await updatePrivateKey(
        {
          id: editForm.id,
          mainCoinType: editForm.mainCoinType,
          feeAddress: originalFeeAddress.value === editForm.feeAddress ? '' : editForm.feeAddress,
          collectAddress: originalCollectAddress.value === editForm.collectAddress ? '' : editForm.collectAddress,
          chainName: chainData[0].chainName,
          code: editForm.code,
        })
    editDialog.value = false
    pageIndex.value = 1
    if (code === 200) {
      // 如果没做修改,不弹提示
      if (originalFeeAddress.value === editForm.feeAddress &&
          originalCollectAddress.value === editForm.collectAddress
      ) {
        editDialog.value = false
      } else {
        ElMessage.success(t('message.EditSuccess'))
      }
    } else {
      ElMessage.error(msg)
    }
  } catch (e) {
    console.log(e)
  } finally {
    resetForm()
    await getList()
  }
}



/***********************************      修改资产 end     *********************************/

// 是否处于节流状态
const isThrottled = ref(false);
// 发送验证码剩余时间
let remainingTime = ref(60);

// 节流函数
function throttle(fn) {
  // 如果处于节流状态，直接返回
  if (isThrottled.value) return;
  isThrottled.value = true;
  fn();
}

// 倒计时函数
function startCountdown(seconds) {
  remainingTime.value = seconds;
  const interval = setInterval(() => {
    remainingTime.value -= 1;
    if (remainingTime.value <= 0) {
      clearInterval(interval);
      isThrottled.value = false;
    }
  }, 1000);
}

// 发送验证码
function getEmailCode(){
  throttle(async () => {
    try {
      const formData = new FormData();
      formData.append('to', userStore.getUserInfo.email);
      await getEmailCodeApi(formData);
      ElMessage.success(t('message.GetCodeSuccess'));
      startCountdown(60);
    } catch(error) {
      console.log('getEmailCodeApi - error', error);
    }
  });
};

// 更新手续费地址
async function updateFeeAddress(row) {
  try {
    let res = await updateFeeAddressApi({
      chainName: row.chainName === "TRX" ? "TRX" : "EVM",
      id: row.id
    });
    if (res.code === 200) {
      ElMessage.success(t('message.EditSuccess'));
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    console.log('updateFeeAddressApi - error', error);
  }
};

// 表单验证规则
const rules = reactive({
  chainId: [
    {required: true, message: t('message.ChainNameNotNull'), trigger: 'blur'},
  ],
  feeAddress: [
    {required: true, message: t('message.FeeAddress'), trigger: 'blur'},
  ],
  collectAddress: [
    {required: true, message: t('message.CollectAddress'), trigger: 'blur'},
  ],
  code: [
    {required: true, message: t('global.PleaseInput') + t('global.emailCode'), trigger: 'blur'},
  ]
})

// 关闭 添加 dialog
const handleCloseAdd = ()=>{
  addDialog.value = false
  form.chainName = undefined
  form.feeAddress = undefined
  form.collectAddress = undefined
}

// 关闭 修改 dialog
const handleCloseEdit = ()=>{
  editDialog.value = false
  editForm.feeAddress = undefined
  editForm.collectAddress = undefined
  editForm.mainCoinType = undefined
  editForm.id = undefined
}

// 查询参数
const queryParams = reactive([
  {
    id: '',
    chainName: '',
    collectAddress: '',
  }
])

// 搜索方法
const onSubmit = (chainName, collectAddress) => {
  // 查询时把 pageIndex 重置为1
  pageIndex.value = 1
  getList(chainName, collectAddress);
}

// 重置查询数据方法
const onReset = () => {
  onClear();
  getList();
}

// 清除  queryParams
const onClear = () => {
  queryParams.id = ''
  queryParams.chainName = ''
  queryParams.collectAddress = ''
}

// 获取资产列表
async function getList(chainName, collectAddress) {
  try {
    console.log(chainName)
    loading.value = true
    const { code, data, msg } = await getPrivateKeyList({
      pageIndex: unref(pageIndex),
      pageSize: unref(pageSize),
      chainName: chainName ? chainName : '' ,
      collectAddress: collectAddress ? collectAddress : ''
    })
    if (code === 200) {
      tableData.value = data.list
      total.value = data.total
    } else {
      ElMessage.error(msg)
    }
  } catch (error) {
    console.log(error)
  } finally{
    loading.value = false
  }
}

// 重置表单
function resetForm() {
  addDialog.value = false;
  editDialog.value = false;
  form.mainCoinType = undefined
  form.feeAddress = undefined
  form.collectAddress = undefined
  form.code = null;
  editForm.mainCoinType = undefined
  editForm.feeAddress = undefined
  editForm.collectAddress = undefined
  editForm.code = null;
}

// 获取配置信息
async function getChainList() {
  const { data } = await getConfigList();
  chainList.value = data;
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

// 分页
const handleCurrentChange = (val) => {
  pageIndex.value = val
  getList()
}

</script>

<style scoped lang="less">
.queryBar{
  background-color: #fff;
  margin: .1rem 0;
  padding: .1rem 0;
  box-sizing: border-box;

  .demo-form-inline{
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
  }

  .query_btns{
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    margin: .15rem 0 0 0;
  }
}
</style>